package com.cf.base.http.interceptor;

import com.cf.base.http.interceptor.headers.HeaderProvider;
import com.cf.base.http.utils.LogUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author yangji
 */
public class HeaderInterceptor implements Interceptor {

    public HeaderInterceptor(HeaderProvider provider) {
        this.provider = provider;
    }

    private static final String TAG = "CF_HeaderInterceptor";

    private HeaderProvider provider;

    @Override
    public Response intercept(Chain chain) throws IOException {

        if (provider == null) {
            return chain.proceed(chain.request());
        }

        Request request = chain.request();

        Request.Builder builder = request.newBuilder();

        String[] configKeys = provider.getHeaderKey();

        Headers requestHeaders = request.headers();


        Headers headers = provider.defaultHeaders();

        String header = null;
        if (headers != null) {
            for (String name : headers.names()) {
                builder.removeHeader(name);
                header = headers.get(name);
                if (header!=null && header.length()>0) {
                    builder.addHeader(name, header);
                } else {
                    //这里存在崩溃 需要记录日志
                    LogUtils.e(TAG, String.format("defaultHeaders %s value == null", name));
                }
            }
        }

        //获取接口单独存在的头
        List<String> configArrays = null;
        if (configKeys != null && configKeys.length > 0) {
            configArrays = new ArrayList<>();
            for (String key : configKeys) {
                if (requestHeaders.names().contains(key)) {
                    configArrays.add(key);
                }
            }
        }

        //填充接口独有的headers
        if (configArrays != null && configArrays.size() > 0) {
            Map<String, String> configHeaders = provider.getHeaderByKey(configArrays);
            if (configHeaders != null) {
                for (String key : configHeaders.keySet()) {
                    header = configHeaders.get(key);
                    builder.removeHeader(key);
                    if (header!=null && header.length()>0) {
                        builder.addHeader(key, header);
                    } else {
                        //这里存在崩溃 需要记录日志
                        LogUtils.e(TAG, String.format("defaultHeaders %s value == null", key));
                    }
                }
            }
        }
        Response response = chain.proceed(builder.build());


        return response;
    }
}
